﻿
function readEntriesAsync(directoryReader) {
    return new Promise((resolve, reject) => {
        directoryReader.readEntries((entries) => {
            resolve(entries);
        }, (error) => {
            reject(error);
        });
    });
}

async function runFileOrDirectory(inputFileElem, files,item) {
    //console.log('runFileOrDirectorys', item);
    if (item.isDirectory) {
        var directoryReader = item.createReader();
        //console.log('directoryReader', directoryReader);
        let entries = await readEntriesAsync(directoryReader);
        //console.log('readEntries', entries);
        for (let entry of entries) {
            //console.log('entry', entry);
            await runFileOrDirectory(inputFileElem, files, entry);
        }
    } else {
        await new Promise((resolve, reject) => {
            item.file((file) => {
                file.fullPath=item.fullPath;
                files.push(file);
                //console.log('file', file);
                //console.log('files.pusehd', files);
                resolve(file);
            }, (error) => {
                reject(error);
            });
        });

    }
    //console.log('runFileOrDirectory.end', item);
}

export function initializeFileDropZone(dropZoneElement, inputFileElem, hoverClass) {
    // Add a class when the user drags a file over the drop zone
    function onDragHover(e) {
        e.preventDefault();
        for (let hc of hoverClass.split(' ')) 
           dropZoneElement.classList.add(hc);
    }

    function onDragLeave(e) {
        e.preventDefault();
        for (let hc of hoverClass.split(' ')) 
            dropZoneElement.classList.remove(hc);
    }

    // Handle the paste and drop events
    async function onDrop(e) {
        e.preventDefault();
        for (let hc of hoverClass.split(' ')) 
            dropZoneElement.classList.remove(hc);

        //console.log('e.dataTransfer.files',
        //    e.dataTransfer.files, e.dataTransfer.items);

        if (e.dataTransfer && e.dataTransfer.items) {
            var items = e.dataTransfer.items;
            //copy items to entrys since the items seems to be removed by the runFileOrDirectory.
            const entrys = [];
            for (var i = 0; i < items.length; i++) {
                var item = items[i].webkitGetAsEntry();
                //console.log('items[i]', i, item);
                if (item) {
                    entrys.push(item);
                }
            }
            //console.log('entrys', entrys);
            const files = [];
            for (var i = 0; i < entrys.length; i++) {
                //console.log('entrys[i]', i, entrys[i]);
                await runFileOrDirectory(inputFileElem, files, entrys[i]);
                //console.log('files', files, files.length, JSON.stringify(files));
            }
            let dataTransfer = new DataTransfer();
            //console.log('dataTransfer.items', dataTransfer.items);
            files.forEach((file) =>{
                //console.log('ff', dataTransfer.items, file);
                dataTransfer.items.add(file);
            });
            inputFileElem.files = dataTransfer.files;
            //console.log('inputFileElem.files', inputFileElem.files);
            const event = new Event('change', { bubbles: true });
            inputFileElem.dispatchEvent(event);
            return;
        }
    }

    function onPaste(e) {
        // Set the files property of the input element and raise the change event
        inputFileElem.files = e.clipboardData.files;
        const event = new Event('change', { bubbles: true });
        inputFileElem.dispatchEvent(event);
    }

    // Register all events
    dropZoneElement.addEventListener("dragenter", onDragHover);
    dropZoneElement.addEventListener("dragover", onDragHover);
    dropZoneElement.addEventListener("dragleave", onDragLeave);
    dropZoneElement.addEventListener("drop", onDrop);
    dropZoneElement.addEventListener('paste', onPaste);

    // The returned object allows to unregister the events when the Blazor component is destroyed
    return {
        dispose: () => {
            dropZoneElement.removeEventListener('dragenter', onDragHover);
            dropZoneElement.removeEventListener('dragover', onDragHover);
            dropZoneElement.removeEventListener('dragleave', onDragLeave);
            dropZoneElement.removeEventListener("drop", onDrop);
            dropZoneElement.removeEventListener('paste', onPaste);
        }
    }
}

export function getFileRelativePathList(inputFileElem) {
    const fileList = [];
    //console.log('f', inputFileElem);
    for (let i = 0; i < inputFileElem.files.length; i++) {
        fileList.push(inputFileElem.files[i].fullPath);
        //console.log('i', i, inputFileElem.files[i]);
    }
    return fileList;
};